<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="header" :style="{ paddingTop: safeAreaInsets.top + 'px' }">
			<view class="header-left" @click="goBack">
				<uni-icons type="left" size="24" color="#666"></uni-icons>
			</view>
			<view class="header-title">确认订单</view>
		</view>

		<!-- 地址区域 -->
		<view class="address-section">
			<view class="address-left">
				<view class="address-header">
					<text class="receiver">{{ address.receiverName || '请添加收货人' }}</text>
					<text class="mobile">{{ address.receiverMobile || '请添加联系电话' }}</text>
				</view>
				<view class="address-content">
					<text class="location">{{ address.location || '请添加所在地区' }}</text>
					<text class="detail">{{ address.detailedAddress || '请添加详细地址' }}</text>
				</view>
			</view>
			<view class="address-right" @click="selectAddress()">
				<uni-icons type="arrowright" size="24" color="#999"></uni-icons>
			</view>
		</view>

		<!-- 商品信息区域 -->
		<view class="goods-section">
			<view class="section-title">商品信息</view>
			<view class="goods-item" v-for="(item, index) in goodsList" :key="index">
				<image :src="item.goodsImage1" class="goods-image" mode="aspectFill"></image>
				<view class="goods-info">
					<view class="name">{{ item.goodsName }}</view>
					<view class="meta">
						<view class="meta-quantity">数量：{{ item.quantity }}</view>
						<view class="quantity-price">单价：¥{{ item.goodsPrice.toFixed(2) }}</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 支付配送区域 -->
		<view class="payment-section">
			<view class="section-title">支付配送</view>
			<view class="option-group">
				<view class="option-item">
					<text>支付方式</text>
					<radio-group @change="paymentMethod = $event.detail.value">
						<label class="radio">
							<radio value="1" :checked="paymentMethod === '1'" color="#e44d26" />
							在线支付
						</label>
						<label class="radio">
							<radio value="2" :checked="paymentMethod === '2'" color="#e44d26" />
							货到付款
						</label>
					</radio-group>
				</view>
				<view class="option-item">
					<text>配送方式</text>
					<radio-group @change="deliveryMethod = $event.detail.value">
						<label class="radio">
							<radio value="1" :checked="deliveryMethod === '1'" color="#e44d26" />
							帆递物流
						</label>
						<label class="radio">
							<radio value="2" :checked="deliveryMethod === '2'" color="#e44d26" />
							鸽鸽速达
						</label>
					</radio-group>
				</view>
				<view class="option-item time-picker">
					<text>送货时间</text>
					<view class="time-select" @click="showTimePicker = true">
						<text>{{ deliveryTime || '立即配送' }}</text>
						<uni-icons type="arrowright" size="18" color="#999"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部操作栏 -->
		<view class="footer-bar">
			<view class="total-box">
				<text class="label">实付款：</text>
				<text class="price">¥{{ actualPayment }}</text>
			</view>
			<view class="btn-group">
				<button class="submit-btn" @click="submitOrder">提交订单</button>
			</view>
		</view>

		<!-- 时间选择器 -->
		<uni-datetime-picker v-if="showTimePicker" type="datetime" @confirm="handleTimeConfirm"
			@cancel="showTimePicker = false" />
	</view>
</template>

<script>
	export default {
		data() {
			return {
				//安全区域
				safeAreaInsets: {
					top: 0
				},
				userId: null,
				goodsList: [],
				selectedAddressId: null,
				address: {
					receiverName: '请选择收货人',
					receiverMobile: '',
					location: '',
					detailedAddress: ''
				},
				totalAmount: 0,
				shippingFee: 0.00,
				discount: 0.00,
				paymentMethod: '1',
				deliveryMethod: '1',
				deliveryTime: '',
				showTimePicker: false
			};
		},
		computed: {
			actualPayment() {
				return (this.totalAmount - this.discount + this.shippingFee).toFixed(2);
			}
		},
		async onLoad(options) {
			if (options.items && options.userId) {
				this.userId = options.userId;
				const items = JSON.parse(decodeURIComponent(options.items));
				await this.loadGoodsDetails(items);
			}
			this.getSafeAreaInsets();
		},
		methods: {
			async loadGoodsDetails(items) {
				try {
					this.goodsList = await Promise.all(items.map(async item => {
						const res = await uni.request({
							url: `http://localhost:8080/goods/goods/${item.goodsId}`,
							header: {
								'Authorization': uni.getStorageSync('token')
							}
						});

						if (res.data.code === 200) {
							return {
								goodsId: item.goodsId,
								quantity: item.quantity || 1,
								goodsName: res.data.data.goodsName,
								goodsPrice: res.data.data.goodsPrice,
								goodsImage1: `http://localhost:8080${res.data.data.goodsImage1}`
							};
						}
						return null;
					}));

					this.goodsList = this.goodsList.filter(item => item);
					this.totalAmount = this.goodsList.reduce((sum, item) =>
						sum + (item.goodsPrice * item.quantity), 0
					);
				} catch (error) {
					uni.showToast({
						title: '商品加载失败',
						icon: 'none'
					});
				}
			},

			generateOrderSn() {
				const now = new Date();
				return [
					now.getFullYear(),
					String(now.getMonth() + 1).padStart(2, '0'),
					String(now.getDate()).padStart(2, '0'),
					String(now.getHours()).padStart(2, '0'),
					String(now.getMinutes()).padStart(2, '0')
				].join('');
			},

			async submitOrder() {
				// 验证地址是否选择
				if (!this.selectedAddressId) {
					uni.showToast({
						title: '请先选择收货地址',
						icon: 'none'
					});
					return;
				}

				try {
					const results = await Promise.all(
						this.goodsList.map(item => uni.request({
							url: 'http://localhost:8080/orderInfo/orderInfo/',
							method: 'POST',
							header: {
								'Authorization': uni.getStorageSync('token'),
								'Content-Type': 'application/json'
							},
							data: {
								orderSn: this.generateOrderSn(),
								userId: this.userId,
								addressId: this.selectedAddressId,
								goodsId: item.goodsId,
								quantity: item.quantity,
								paymentAmount: item.goodsPrice * item.quantity,
								orderStatus: 1
							}
						}))
					);

					// 检查所有请求是否成功
					if (results.every(res => res.data.code === 200)) {
						uni.redirectTo({
							url: '/pages/order-payment/pay-success'
						});
					} else {
						throw new Error('部分订单创建失败');
					}
				} catch (error) {
					uni.showToast({
						title: '订单提交失败',
						icon: 'none'
					});
				}
			},

			goBack() {
				uni.navigateBack();
			},

			selectAddress() {
				uni.navigateTo({
					url: '/pages/shop-address/shop-address',
					events: {
						// 监听地址选择事件
						addressSelected: (data) => {
							this.selectedAddressId = data.addressId;
							this.address = {
								receiverName: data.receiverName,
								receiverMobile: data.receiverMobile,
								location: data.location,
								detailedAddress: data.detailedAddress
							};
						}
					}
				});
			},

			handleTimeConfirm(e) {
				this.deliveryTime = e;
				this.showTimePicker = false;
			},

			//安全区域
			getSafeAreaInsets() {
				uni.getSystemInfo({
					success: (res) => {
						this.safeAreaInsets.top = res.safeArea?.top ?? res.statusBarHeight
					}
				});
			}
		}
	};
</script>

<style scoped>
	.container {
		/* padding-bottom: 100px;
		background: #f8f8f8; */

		padding-bottom: 100px;
		background: #FFF8F0;
	}

	.header {
		/* 	display: flex;
		align-items: center;
		padding: 15px;
		background: #fff;
		border-bottom: 1px solid #eee; */

		display: flex;
		align-items: center;
		padding: 0 30rpx;
		height: 90rpx;
		background: #fff;
		/* border-bottom: 1px solid #eee; */
		margin-bottom: 10px;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.2);
	}

	.address-section {
		/* 	display: flex;
		align-items: center;
		margin: 15px;
		padding: 16px;
		background: #fff;
		border-radius: 12px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05); */

		display: flex;
		align-items: center;
		margin: 15px;
		/* padding: 16px; */
		background: #fff;
		border-radius: 12px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
		width: 96%;
		margin: 0 auto 10px;
	}

	.goods-section {
		/* 	margin: 15px;
		background: #fff;
		border-radius: 8px; */

		background: #fff;
		border-radius: 10px;
		width: 96%;
		margin: 0 auto;
		padding: 10px 0;
		margin-bottom: 10px;
	}

	.section-title {
		margin-bottom: 10px;
		margin-left: 10px;
	}

	.goods-item {
		/* 	display: flex;
		padding: 15px;
		border-bottom: 1px solid #f5f5f5; */

		display: flex;
		/* padding: 15px; */
		/* border-bottom: 1px solid #f5f5f5; */
		margin-left: 10px;
		margin-bottom: 10px;
	}

	.footer-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 60px;
		background: #fff;
		display: flex;
		align-items: center;
		padding: 0 15px;
		box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.08);
	}

	.submit-btn {
		background: linear-gradient(135deg, #ff6b6b, #e44d26);
		color: #fff;
		height: 44px;
		line-height: 44px;
		padding: 0 35px;
		border-radius: 22px;
		font-size: 16px;
		box-shadow: 0 4px 12px rgba(228, 77, 38, 0.2);
	}

	/* 其他样式保持原样 */
	.header-title {
		flex: 1;
		text-align: center;
		font-size: 16px;
		font-weight: 500;
	}

	.address-left {
		/* flex: 1;
		padding-right: 12px; */

		flex: 1;
		/* padding-right: 12px; */
		margin-left: 10px;
		padding: 10px 0;
	}

	.address-right {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 24px;
	}

	.address-header {
		display: flex;
		align-items: center;
		margin-bottom: 10px;
		/* padding: 0 30rpx; */
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.receiver {
		font-size: 14px;
		font-weight: 500;
		color: #333;
		margin-right: 12px;
		max-width: 60%;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.mobile {
		font-size: 14px;
		color: #666;
		flex: 1;
	}

	.address-content {
		/* line-height: 1.4; */

		display: flex;
	}

	.location {
		/* display: block;
		font-size: 14px;
		color: #444;
		margin-bottom: 4px; */

		font-size: 14px;
		color: #333;
		margin-bottom: 4px;
		margin-right: 10px;
	}

	.detail {
		font-size: 14px;
		color: #666;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
	}

	.goods-image {
		width: 80px;
		height: 80px;
		border-radius: 6px;
		margin-right: 12px;
	}

	.name {
		font-size: 14px;
		margin-bottom: 8px;
	}

	.meta {
		/* display: flex; */
		justify-content: space-between;
		color: #666;
		font-size: 16px;
	}

	.meta-quantity {
		font-size: 14px;
		/* color: #f40; */
	}

	.quantity-price {
		font-size: 14px;
		color: #f40;
	}

	.price {
		color: #e44d26;
		font-weight: 500;
		font-size: 14px;
	}

	.payment-section {
		/* 		margin: 15px;
		background: #fff;
		border-radius: 8px; */

		background: #fff;
		border-radius: 8px;
		width: 96%;
		margin: 0 auto;
		padding: 10px 0;
	}

	.option-group {
		/* padding: 0 15px; */
	}

	.option-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 12px 0;
		border-bottom: 1px solid #f5f5f5;

		margin-left: 10px;
		margin-right: 10px;
	}

	.radio {
		margin-left: 15px;
	}

	.time-select {
		display: flex;
		align-items: center;
		color: #666;
	}

	.total-box {
		flex: 1;
		display: flex;
		align-items: baseline;
	}

	.label {
		font-size: 14px;
		color: #666;
		margin-right: 6px;
	}

	.price {
		font-size: 18px;
		font-weight: 600;
		color: #e44d26;
	}

	.submit-btn:active {
		transform: scale(0.98);
		opacity: 0.9;
	}
</style>
